#ifndef ANT_COLONY_H
#define ANT_COLONY_H

#endif // ANT_COLONY_H
#pragma once
//#include "rectangle.h"
#include "utils.h"
#include<algorithm>
#include<math.h>
#include<stdlib.h>
#include "data.h"
#include "pheromone_map.h"
#include <algorithm>
#include<time.h>
#include<vector>
#include<map>
#include<iostream>
#include<functional>
#include<algorithm>
#include<ctime>
#include "ant.h"
#define INT_MAX 2147483647

float RAN3=0.65;//0.7的概率随机
class ant_colony
{
public:
    vector<ant*> ants;
    int best_ant_index;
    static int minarea_now;
    ant_colony(vector<ant*> ants)
    {
        this->ants = ants;
    }
    ant_colony() {}
    ~ant_colony();
    ant_colony(vector<rectangle*>, int);//初始化num只蚂蚁
    void ants_run(bool first, const vector<rectangle*>& r);
    int find_min_area();
};
int ant_colony::minarea_now = 2147483647;

ant_colony::ant_colony(vector<rectangle*> rt_v_, int num)
{
    vector<rectangle*> temp;
    for (int i = 0; i < rt_v_.size(); i++)
    {
        rectangle *r2 = rt_v_[i]->get_copy();
        temp.push_back(r2);
    }
    for (int i = 0; i < num; i++)
        ants.push_back(new ant(temp));

}

ant_colony::~ant_colony()
{
    for(int i=0;i<ants.size();i++)
    {
        delete ants[i];
    }
}
void ant_colony::ants_run(bool first,const vector<rectangle*>& r)
{
    int area_sum = 0;
    for (int i = 0; i < r.size(); ++i) {
        area_sum += r[i]->area;
    }
    for (int i = 0; i < ants.size(); i++)
    {
        //摆放第一步，目前只更新全局信息素
        ants[i]->first_step(first);
        ants[i]->set_first_rctangle();
        //循环摆放剩下所有矩形
        while (ants[i]->Time != ants[i]->rt_v.size())
        {
            if (first||ant::stochastic_decision01(RAN3))
                ants[i]->select_next_rctangle(first,area_sum);
            else
                ants[i]->select_next_rctangle1(first);
        }

    }
}

//找到每轮最小面积并更新信息素
int ant_colony::find_min_area()
{
    int min_area = INT_MAX;
    int index;//记录精英蚂蚁的下标
    for (int i = 0; i < ants.size(); i++)
    {
        if (ants[i]->breadthFirstSearch() < min_area)
        {
            min_area = ants[i]->breadthFirstSearch();
            index = i;
        }
    }

    if (min_area <= minarea_now)//只有下降才更新
    {
        ants[index]->bfs_updata_map();//精英蚂蚁更新信息素表
        minarea_now = min_area;
    }
    //cout << "该轮最小面积" << min_area<<endl;
    //cout << "最小面积的蚂蚁是第" << index << "个" << endl;
    ants[index]->breadthFirstSearch();
    best_ant_index = index;
    return min_area;
}
